package org.je.image;

import java.awt.image.BufferedImage;

/**
 * 类ImageFilter
 * 
 * @author fanyifeng 2012-11-8 上午10:56:56
 */
public class ImageFilter
{

	/**
	 * @param img
	 * @param alpha
	 *            must between 0 and 255
	 */
	public static void updateAlpha(BufferedImage img, int alpha) {
		int w = img.getWidth();
		int h = img.getHeight();
		for (int y = 0; y < h; ++y) {
			for (int x = 0; x < w; ++x) {
				int argb = img.getRGB(x ,y);
				if ( ( (argb & 0xff000000) >>> 24) < 11) {
					img.setRGB(x ,y ,0);
				} else {
					img.setRGB(x ,y , (argb & 0xffffff) | (alpha << 24));
				}
			}
		}
	}

	/**
	 * @param img
	 * @param minCf
	 */
	public static void deleteLower(BufferedImage img, int minCf) {
		int w = img.getWidth();
		int h = img.getHeight();
		for (int y = 0; y < h; ++y) {
			for (int x = 0; x < w; ++x) {
				int argb = img.getRGB(x ,y);
				int a = (0xff000000 & argb) >>> 24;
				int r = (0xff0000 & argb) >> 16;
				int g = (0x00ff00 & argb) >> 8;
				int b = 0xff & argb;
				img.setRGB(x ,y ,filterLowerARGB(a ,r ,g ,b ,minCf));
			}
		}
	}

	private static int filterLowerARGB(int alpha, int red, int green, int blue, int minCf) {
		if (alpha < 11 || (red < minCf && green < minCf && blue < minCf)) {
			return 0;
		}
		return alpha << 24 | red << 16 | green << 8 | blue;
	}
}
